﻿// © 2009 Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.NotificationsService;
using Microsoft.Security.Application;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;
using System.Text.RegularExpressions;

namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks
{
    public partial class CreateNotificationSchedule : System.Web.UI.UserControl
    {
        List<NotificationContent> lstContents = new List<NotificationContent>();
        NotificationSchedule schedule = null;

        public global::System.Web.UI.WebControls.TextBox txtName;
        public global::System.Web.UI.WebControls.ListBox lstNotifications;

        public NotificationSchedule NotificationSchedule 
        {
            set { 
                schedule = value; 
                if (schedule != null) 
                { 
                    this.DoDataBind();
                    this.txtName.Text = schedule.Name;
                    ViewState["NotificationSchedule"] = schedule; 
                } 
            }
            get { return schedule; }
        }

        public string HeaderText 
        {
            set { lblPageHeader.Text = value; }
            get { return lblPageHeader.Text; }
        }

        public bool IsEditing
        {
            set { ViewState["IsScheduleEditing"] = value; }
            get 
            { 
                if (ViewState["IsScheduleEditing"]!=null) {
                    return  (bool)ViewState["IsScheduleEditing"];
                   }
                else
                    return false;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.ToggleTypePanels(rbtnListType.Items[0].Selected);
            this.ToggleFrequencyPanels(int.Parse(rbtnListFrequency.Items[rbtnListFrequency.SelectedIndex].Value));
            if (ViewState["NotificationContents"] == null)
            {
                lstContents = new List<NotificationContent>();
                NotificationsServiceClient notClient = new NotificationsServiceClient();
                lstContents.AddRange(notClient.GetNotificationContents());
                notClient.Close();
                ViewState["NotificationContents"] = lstContents;
            }
            else
            {
                lstContents = (List<NotificationContent>)ViewState["NotificationContents"];
            }
            if (ViewState["NotificationSchedule"] == null)
            {
                schedule = new NotificationSchedule();
                schedule.Notifications = new Notification[] { };
            }
            else
            {
                schedule = (NotificationSchedule)ViewState["NotificationSchedule"];
            }

            if (!this.IsPostBack)
            {
                this.DoDataBind(); 
            }
        }

        private void DoDataBind()
        {
            ddlContents.DataTextField = "Name";
            ddlContents.DataValueField = "ID";
            ddlContents.DataSource = lstContents;
            ddlContents.DataBind();

            lstNotifications.DataTextField = "Subject";
            lstNotifications.DataValueField = "ID";
            lstNotifications.DataSource = schedule.Notifications;
            lstNotifications.DataBind();

            if ((lstNotifications.Items.Count > 0) && (lstNotifications.SelectedIndex < 0))
            {
                lstNotifications.SelectedIndex = 0;
            }
        }

        private void ToggleTypePanels(bool showRecurring)
        {
            pnlRecurring.Visible = showRecurring;
            pnlFixed.Visible = !showRecurring;
        }

        private void ToggleFrequencyPanels(int selectedFrequency)
        {
            pnlFreqDaily.Visible = false;
            pnlFreqWeekly.Visible = false;
            pnlFreqMonthly.Visible = false;
            switch (selectedFrequency)
            {
                case 1:
                    pnlFreqDaily.Visible = true;
                    break;
                case 2:
                    pnlFreqWeekly.Visible = true;
                    break;
                case 3:
                    pnlFreqMonthly.Visible = true;
                    break;
            }
        }

        protected void btnNotificationSave_OnClick(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtTo.Text) || txtTo.Text.Trim() == "Other - Type Here") 
                {
                    Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOT_RECEP_VALID"), "Error", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtSubject.Text) || txtSubject.Text.Trim() == "")
                {
                    Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOT_SUBJECT_NOT_VALID"), "Error", true);
                    return;
                }

                if (txtTo.Text.Trim() !="$TaskOwner$" && !Regex.IsMatch(txtTo.Text, Utility.GetConfigurationValue("EmailRegex")))
                {
                    Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOT_RECEP_VALID"), "Error", true);
                    return;
                }

                /* Add by v-weqiu for validating more conditions on 07/22/2009 */
                if (rbtnListType.SelectedValue.Equals("Recurring", StringComparison.InvariantCultureIgnoreCase))
                {
                    // Recurring
                    if (rbtnListFrequency.SelectedValue.Equals("1", StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Daily
                        if (string.IsNullOrEmpty(txtDailyDays.Text.Trim()))
                        {
                            Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOTIFICATION_DAY_REQUIRED"), "Error", true);
                            return;
                        }
                    }
                    else if (rbtnListFrequency.SelectedValue.Equals("2", StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Weekly
                        if (string.IsNullOrEmpty(txtWeeklyWeeks.Text.Trim()))
                        {
                            Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOTIFICATION_WEEK_REQUIRED"), "Error", true);
                            return;
                        }
                        if (string.IsNullOrEmpty(chkListWeeklyDays.SelectedValue))
                        {
                            Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOTIFICATION_DAY_REQUIRED"), "Error", true);
                            return;
                        }
                    }
                    else if (rbtnListFrequency.SelectedValue.Equals("3", StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Monthly
                        if (string.IsNullOrEmpty(txtMonthlyDayOfMonth.Text.Trim()))
                        {
                            Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOTIFICATION_DAY_REQUIRED"), "Error", true);
                            return;
                        }
                        if (string.IsNullOrEmpty(txtMonthlyMonths.Text.Trim()))
                        {
                            Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOTIFICATION_MONTH_REQUIRED"), "Error", true);
                            return;
                        }
                    }
                    if (rbtnEndAfterOccurnaces.Checked)
                    {
                        // Occurance
                        if (string.IsNullOrEmpty(txtOccurances.Text.Trim()))
                        {
                            Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOTIFICATION_OCCURANCE_REQUIRED"), "Error", true);
                            return;
                        }
                    }
                }
                else if (rbtnListType.SelectedValue.Equals("Fixed", StringComparison.InvariantCultureIgnoreCase))
                {
                    // Fixed
                    if (rbtnFixedBeforeDueDate.Checked)
                    {
                        if (string.IsNullOrEmpty(txtDaysBeforeDueDate.Text.Trim()))
                        {
                            Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOTIFICATION_DAY_REQUIRED"), "Error", true);
                            return;
                        }
                    }
                    else if (rbtnFixedAfterDueDate.Checked)
                    {
                        if (string.IsNullOrEmpty(txtDaysAfterDueDate.Text.Trim()))
                        {
                            Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "NOTIFICATION_DAY_REQUIRED"), "Error", true);
                            return;
                        }
                    }
                }

                Notification newNotification = null;
                List<Notification> lstNots = schedule.Notifications.ToList();
                if ((bool)ViewState["IsEditing"])
                {
                    if (ViewState["NotificationID"] != null)
                    {
                        foreach (Notification not in lstNots)
                        {
                            if (not.ID == int.Parse(ViewState["NotificationID"].ToString()))
                            {
                                newNotification = not;
                                break;
                            }
                        }
                    }
                }
                else
                    newNotification = new Notification();
                if (newNotification != null)
                {
                    newNotification.Subject = txtSubject.Text;
                    newNotification.Recipients = new NotificationRecipient[1];
                    newNotification.Recipients[0] = new NotificationRecipient();
                    newNotification.Recipients[0].Address = txtTo.Text;
                    newNotification.Recipients[0].LastUpdatedBy = Utility.GetUserFullName();
                    newNotification.Recipients[0].Type = 1;
                    newNotification.NotificationContent = new NotificationContent();
                    newNotification.NotificationContent.ID = int.Parse(ddlContents.SelectedValue);
                    newNotification.IsRecurring = rbtnListType.Items[0].Selected;
                    if (rbtnListType.Items[0].Selected)
                    {
                        switch (int.Parse(rbtnListFrequency.SelectedValue))
                        {
                            case 1:
                                newNotification.FrequencyType = FrequencyType.Daily;
                                newNotification.Frequency = int.Parse(txtDailyDays.Text);
                                break;
                            case 2:
                                newNotification.FrequencyType = FrequencyType.Weekly;
                                newNotification.Frequency = int.Parse(txtWeeklyWeeks.Text);
                                DaysOfWeek selectedWeekdays = DaysOfWeek.None;
                                foreach (ListItem li in chkListWeeklyDays.Items)
                                {
                                    if (li.Selected == true)
                                    {
                                        selectedWeekdays = selectedWeekdays | (DaysOfWeek)int.Parse(li.Value);
                                    }
                                }
                                newNotification.DayOfWeek = selectedWeekdays;
                                break;
                            case 3:
                                newNotification.FrequencyType = FrequencyType.Monthly;
                                newNotification.Frequency = int.Parse(txtMonthlyMonths.Text);
                                newNotification.DayOfMonth = int.Parse(txtMonthlyDayOfMonth.Text);
                                break;
                        }

                        newNotification.IsBeforeDueDate = rbtnEndByDueDate.Checked;
                    }
                    else if (rbtnListType.Items[1].Selected)
                    {
                        if (rbtnFixedBeforeDueDate.Checked)
                            newNotification.Frequency = int.Parse(txtDaysBeforeDueDate.Text);
                        else if (rbtnFixedAfterDueDate.Checked)
                            newNotification.Frequency = int.Parse(txtDaysAfterDueDate.Text);

                        newNotification.IsBeforeDueDate = rbtnFixedBeforeDueDate.Checked;
                    }

                    if (rbtnEndAfterOccurnaces.Checked)
                        newNotification.Occurances = int.Parse(txtOccurances.Text);

                    if (rbtnNoEndDate.Checked)
                        newNotification.Occurances = 0;

                    newNotification.LastUpdatedBy = Utility.GetUserFullName();

                    if (!(bool)ViewState["IsEditing"])
                    {
                        newNotification.ID = newNotification.GetHashCode();
                        lstNots.Add(newNotification);
                    }
                    schedule.Notifications = lstNots.ToArray();
                    ViewState["NotificationSchedule"] = schedule;
                    this.DoDataBind();
                    mpeAddNotification.Hide();
                }
            }
            catch
            {
                Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_SAVE_UNKWNERR"), "Error", true);
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            ViewState["IsEditing"] = false;
            lblHeader.Text = "Add Notification";
            this.ClearControls();
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstNotifications.SelectedItem != null)
                {
                    foreach (Notification not in schedule.Notifications)
                    {
                        if (not.ID == int.Parse(lstNotifications.SelectedItem.Value))
                        {
                            ViewState["NotificationID"] = not.ID.ToString();
                            ViewState["IsEditing"] = true;
                            lblHeader.Text = "Edit Notification";
                            this.ClearControls();

                            txtSubject.Text = not.Subject;
                            txtTo.Text = not.Recipients[0].Address;
                            ddlContents.SelectedIndex = ddlContents.Items.IndexOf(ddlContents.Items.FindByValue(not.NotificationContent.ID.ToString()));
                            rbtnListType.Items[0].Selected = not.IsRecurring;
                            rbtnListType.Items[1].Selected = !not.IsRecurring;
                            if (not.IsRecurring)
                            {
                                switch (not.FrequencyType)
                                {
                                    case FrequencyType.Daily:
                                        rbtnListFrequency.SelectedIndex = 0;
                                        txtDailyDays.Text = not.Frequency.ToString();
                                        break;
                                    case FrequencyType.Weekly:
                                        rbtnListFrequency.SelectedIndex = 1;
                                        txtWeeklyWeeks.Text = not.Frequency.ToString();
                                        chkListWeeklyDays.ClearSelection();
                                        foreach (ListItem li in chkListWeeklyDays.Items)
                                        {
                                            li.Selected = ((not.DayOfWeek & (DaysOfWeek)(int.Parse(li.Value))) == (DaysOfWeek)(int.Parse(li.Value)));
                                        }
                                        break;
                                    case FrequencyType.Monthly:
                                        rbtnListFrequency.SelectedIndex = 2;
                                        txtMonthlyMonths.Text = not.Frequency.ToString();
                                        txtMonthlyDayOfMonth.Text = not.DayOfMonth.ToString();
                                        break;
                                }

                                if (not.IsBeforeDueDate)
                                    rbtnEndByDueDate.Checked = true;
                                else
                                    if (not.Occurances == 0)
                                        rbtnNoEndDate.Checked = true;
                                    else
                                    {
                                        rbtnEndAfterOccurnaces.Checked = true;
                                        txtOccurances.Text = not.Occurances.ToString();
                                    }
                            }
                            else
                            {
                                if (not.IsBeforeDueDate)
                                {
                                    rbtnFixedBeforeDueDate.Checked = true;
                                    txtDaysBeforeDueDate.Text = not.Frequency.ToString();
                                }
                                else
                                {
                                    rbtnFixedAfterDueDate.Checked = true;
                                    txtDaysAfterDueDate.Text = not.Frequency.ToString();
                                }
                            }


                            ToggleFrequencyPanels(int.Parse(rbtnListFrequency.SelectedValue));
                            ToggleTypePanels(rbtnListType.Items[0].Selected);
                            mpeAddNotification.Show();
                            break;
                        }
                    }
                }
            }
            catch
            {
                Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_SAVE_UNKWNERR"), "Error", true);
            }
        }

        public void ClearControls()
        {
            txtSubject.Text = "";
            txtTo.Text = "";
            if (ddlContents.Items.Count >0)
                ddlContents.SelectedIndex = 0;  
            rbtnListType.SelectedIndex = 0;
            rbtnListFrequency.SelectedIndex = 0;
            txtDailyDays.Text = "";
            txtWeeklyWeeks.Text = "";
            chkListWeeklyDays.ClearSelection();
            txtMonthlyMonths.Text = "";
            txtMonthlyDayOfMonth.Text = "";
            rbtnFixedBeforeDueDate.Checked = true;
            txtDaysBeforeDueDate.Text = "";
            txtDaysAfterDueDate.Text = "";

            rbtnEndByDueDate.Checked = true;
            rbtnEndAfterOccurnaces.Checked = false;
            txtOccurances.Text = "";
            rbtnNoEndDate.Checked = false;
            this.DoDataBind();
            ToggleFrequencyPanels(int.Parse(rbtnListFrequency.SelectedValue));
            ToggleTypePanels(rbtnListType.Items[0].Selected);
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (lstNotifications.SelectedItem != null)
            {
                Notification notification = null;
                foreach (Notification not in schedule.Notifications)
                {
                    if (not.ID == int.Parse(lstNotifications.SelectedItem.Value))
                    {
                        notification = not;
                        break;
                    }
                }
                List<Notification> lstNots = schedule.Notifications.ToList();
                if (lstNots.Contains(notification))
                {
                    lstNots.Remove(notification);
                    schedule.Notifications = lstNots.ToArray();
                    ViewState["NotificationSchedule"] = schedule;
                    this.DoDataBind();
                }
            }
        }

        public void Save()
        {
            NotificationsServiceClient notClient = new NotificationsServiceClient();
            schedule.Name = txtName.Text;
            schedule.LastUpdatedBy = Utility.GetUserFullName();
            schedule.LastUpdatedDate = DateTime.UtcNow;
            schedule.CreatedBy = new User();
            schedule.CreatedBy.ID = ((CISF.Security.Principal.CISFIdentity)Context.User.Identity).PersonId;
            schedule.TaskCount = 0;
            if (IsEditing)
                notClient.UpdateNotificationSchedule(schedule);
            else
                schedule.ID = notClient.AddNotificationSchedule(schedule);
            notClient.Close();
        }
    }
}